package flexo.graphic;

import java.util.HashMap;

import flexo.file.File;
import flexo.file.Node;
import flexo.math.Coords;

public class SpriteSheet extends flexo.common.ReferenceCount
{
	protected String name;
	protected int texWidth,texHeight;
	protected float frameWidth,frameHeight;
	protected float aspectRatio;
	protected int xFrames, yFrames;
	protected int fps;
	protected HashMap<String,int[]> animations;
	
	public SpriteSheet(String file)
	{
		animations = new HashMap<String, int[]>();
		
		// First the descriptionFile is loaded
		flexo.file.FileSystem fs = (flexo.file.FileSystem)flexo.Kernel.getSystem(flexo.file.FileSystem.ID);
		File desc = fs.createFile(file);
 		desc.load(new flexo.file.reader.Xml());
		
		Node sprite = desc.getRootNode().getChild("sprite");
		name = sprite.getProperty("name").getStringValue();
		
		flexo.Kernel.log("flexo.graphic.SpriteSheet", "Creating spritesheet '"+name+"'");
		
		texWidth = sprite.getProperty("texWidth").getIntValue();
		texHeight = sprite.getProperty("texHeight").getIntValue();
		frameWidth = sprite.getProperty("frameWidth").getIntValue();		
		frameHeight = sprite.getProperty("frameHeight").getIntValue();
		aspectRatio = frameWidth / frameHeight;
		frameWidth /= (float) texWidth;
		frameHeight /= (float) texHeight;
		xFrames = sprite.getProperty("xFrames").getIntValue();
		yFrames = sprite.getProperty("yFrames").getIntValue();
		fps = sprite.getProperty("fps").getIntValue();
		
		for (int i = 0; i < sprite.getChildrenCount(); ++i)
		{
			Node animation = sprite.getChild(i);
			int[] frameList = new int[animation.getChildrenCount()];
			for (int j = 0; j < animation.getChildrenCount(); ++j)
			{
				frameList[j] = animation.getChild(j).getProperty("text").getIntValue();
			}
			animations.put(animation.getProperty("name").getStringValue(), frameList);
		}		
	}
	
	public String getName()
	{
		return name;
	}
	
	public int fillTexCoords(String animation, int frame, Coords upperLeft, Coords lowerRight)
	{
		int[] frameList = this.animations.get(animation);
		int realFrame = frameList[frame];

		int x = realFrame % xFrames;
		int y = realFrame / xFrames;
		
		upperLeft.x = x * frameWidth;
		upperLeft.y = y * frameHeight;
		
		lowerRight.x = upperLeft.x + frameWidth;
		lowerRight.y = upperLeft.y + frameHeight;
		
		if (frame < frameList.length - 1)
		{
			return ++frame;
		}
		else
		{
			return 0;
		}
	}
	
	public int getFPS()
	{
		return fps;
	}
	
	public float getAspectRatio()
	{
		return aspectRatio;
	}

	@Override
	protected void destroy()
	{
		flexo.graphic.GraphicSystem gs = (flexo.graphic.GraphicSystem)flexo.Kernel.getSystem(flexo.graphic.GraphicSystem.ID);
		gs.spriteSheetPool.remove(this);
	}
}
